package com.century.sjt.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.century.sjt.Constant;
import com.century.sjt.EMChat.adapter.EaseContactAdapter;
import com.century.sjt.EMChat.db.InviteMessgeDao;
import com.century.sjt.EMChat.domain.EaseUser;
import com.century.sjt.EMChat.widget.EaseSidebar;
import com.century.sjt.R;
import com.century.sjt.SjtHelper;
import com.century.sjt.activity.Topic.MyTopActivity;
import com.century.sjt.util.TipUtil;
import com.century.sjt.widget.TitleBar.SjtTitleBar;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by 炳基 on 2016/5/30.
 * 关注的商家列表
 */
public class ShopContacListActivity extends BaseActivity {
    private ListView listView;
    private EaseSidebar sidebar;
    protected EaseContactAdapter contactAdapter;
    private List<EaseUser> contactList;

    private EditText queryEditText;
    protected SwipeRefreshLayout swipeRefreshLayout;
    private SjtTitleBar titleBar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sjt_shop_contaclist_activity);
        initView();
        initEvent();

    }


    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void initView() {
        titleBar = (SjtTitleBar) findViewById(R.id.title_bar);
        titleBar.setTitle(getResources().getString(R.string.text_focus_on_shop));
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        listView = (ListView) findViewById(R.id.list);
        sidebar = (EaseSidebar) findViewById(R.id.sidebar);
        sidebar.setListView(listView);
        queryEditText= (EditText) findViewById(R.id.query);
        //刷新组件
        swipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.list_refesh);

        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light,
                android.R.color.holo_orange_light, android.R.color.holo_red_light);
    }

    @Override
    protected void initEvent() {
        contactList = new ArrayList<EaseUser>();
        // 获取设置contactlist
        getContactList();
        // 设置adapter
        contactAdapter = new EaseContactAdapter(this, R.layout.ease_row_contact, contactList);
        listView.setAdapter(contactAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                onListItemClick(position);
            }
        });
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                showAppayRes(contactList.get(position));
                return true;
            }
        });
        listView.setOnScrollListener(new AbsListView.OnScrollListener(){
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i)
            {
            }

            @Override
            public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount)
            {
                View firstView = absListView.getChildAt(firstVisibleItem);
                if (firstVisibleItem == 0 && (firstView == null || firstView.getTop() == 0))
                    swipeRefreshLayout.setEnabled(true);
                else
                    swipeRefreshLayout.setEnabled(false);
            }
        });

        queryEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (queryEditText.getText().length()==0||"".equals(queryEditText.getText().toString())){
                    getContactList();
                }else {
                    seabarUser(queryEditText.getText().toString().trim());
                }
                contactAdapter.notifyDataSetChanged();
            }

        });
        //        下拉刷新
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
//                setOnRefresh();
//                refresh();
                SjtHelper.getInstance().updateFetchContacts();
                if (SjtHelper.getInstance().isSyncingGroupsWithServer()==false){
                    getContactList();
                    swipeRefreshLayout.setRefreshing(false);
                }
                contactAdapter.notifyDataSetChanged();

            }
        });
    }

    protected void onListItemClick(int position) {
        //跳转到商家个人首页
        startActivity(new Intent(ShopContacListActivity.this, MyTopActivity.class).putExtra("username",contactList.get(position).getUsername()));

//		if (position != 0) {
//
//        }
    }

    public void back(View view) {
        finish();
    }

    private void getContactList() {
        contactList.clear();
        Map<String, EaseUser> users = SjtHelper.getInstance().getContactList();
        Iterator<Map.Entry<String, EaseUser>> iterator = users.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, EaseUser> entry = iterator.next();
            if (!entry.getKey().equals(Constant.NEW_FRIENDS_USERNAME) && !entry.getKey().equals(Constant.GROUP_USERNAME) && !entry.getKey().equals(Constant.CHAT_ROOM) && !entry.getKey().equals(Constant.CHAT_ROBOT))
                if (!"00000000".equals(entry.getKey())){
                    if ("1".equals(entry.getValue().getIsShop())){
                        contactList.add(entry.getValue());
                    }

                }

        }
        // 排序
        Collections.sort(contactList, new Comparator<EaseUser>() {

            @Override
            public int compare(EaseUser lhs, EaseUser rhs) {
                if (lhs.getInitialLetter().equals(rhs.getInitialLetter())) {
                    return lhs.getNick().compareTo(rhs.getNick());
                } else {
                    if ("#".equals(lhs.getInitialLetter())) {
                        return 1;
                    } else if ("#".equals(rhs.getInitialLetter())) {
                        return -1;
                    }
                    return lhs.getInitialLetter().compareTo(rhs.getInitialLetter());
                }

            }
        });
    }

    @Override
    protected void initData() {

    }

    public void showAppayRes(final EaseUser user) {
        //询问是否取消
        AlertDialog.Builder builder = new AlertDialog.Builder(ShopContacListActivity.this);
        builder.setTitle(getResources().getString(R.string.text_prompt));
        builder.setMessage(getResources().getString(R.string.text_delete_merchant));
        builder.setPositiveButton(getResources().getString(R.string.btn_yes), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                sjtDeleteContact(user);

            }
        });
        builder.setNegativeButton(getResources().getString(R.string.btn_no), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setCancelable(false);
        builder.create().show();
    }
    private void sjtDeleteContact(final EaseUser tobeDeleteUser) {

        //显示Progress Dialog
        TipUtil.openProgressDialog(com.century.sjt.util.Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), ShopContacListActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, com.century.sjt.util.Constant.DeleteFriend, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.log("删除联系人接口成功返回"+tobeDeleteUser.getUsername().toString(), response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
                        TipUtil.closeProgressDialog();
                        contactList.remove(tobeDeleteUser);
                        contactAdapter.notifyDataSetChanged();
                        TipUtil.showToast(getResources().getString(R.string.text_delete_concerns_success), ShopContacListActivity.this, 1);
                        InviteMessgeDao dao = new InviteMessgeDao(ShopContacListActivity.this);
                        dao.deleteMessage(tobeDeleteUser.getUsername());

                    }else if (code.equals("501")) {//服务器找不到好友
                        TipUtil.closeProgressDialog();
                        TipUtil.showToast(getResources().getString(R.string.text_delete_concerns_fail), ShopContacListActivity.this, 1);

                    } else {//失败
                        TipUtil.showToast(message, ShopContacListActivity.this, 1);
                    }
                } catch (JSONException ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service),ShopContacListActivity.this, 1);
                }
                TipUtil.closeProgressDialog();

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), ShopContacListActivity.this, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences =getSharedPreferences(com.century.sjt.util.Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                String mobile = mainSharedPreferences.getString("mobile", "");
                map.put("loginId", userId);
                map.put("userId",userId);
                map.put("friendId", tobeDeleteUser.getUsername());
//                map.put("mobile", mobile);
                return map;

            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(com.century.sjt.util.Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
//                Log.e("cookie", cookieValue);
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);
    }

    /**
     * list 模糊搜索好友
     */
    public void seabarUser(final String srcName){
        for(int i=0;i<contactList.size();i++ ){
            if(((EaseUser)(contactList.get(i))).getNick().indexOf(srcName)<=-1){
                contactList.remove(i);
                }
        }
        // 排序
        Collections.sort(contactList, new Comparator<EaseUser>() {

            @Override
            public int compare(EaseUser lhs, EaseUser rhs) {
                if (lhs.getInitialLetter().equals(rhs.getInitialLetter())) {
                    return lhs.getNick().compareTo(rhs.getNick());
                } else {
                    if ("#".equals(lhs.getInitialLetter())) {
                        return 1;
                    } else if ("#".equals(rhs.getInitialLetter())) {
                        return -1;
                    }
                    return lhs.getInitialLetter().compareTo(rhs.getInitialLetter());
                }

            }
        });

    }
}
